package com.baizhi.service.impl;

import cn.hutool.json.JSONUtil;
import com.baizhi.config.ElasticSearchConfig;
import com.baizhi.entity.CmfzArticle;
import com.baizhi.entity.CmfzGuru;
import com.baizhi.mapper.CmfzArticleMapper;
import com.baizhi.mapper.CmfzGuruMapper;
import com.baizhi.service.CmfzArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.formula.functions.T;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljh
 * @since 2020-08-18
 */
@Service
public class CmfzArticleServiceImpl extends ServiceImpl<CmfzArticleMapper, CmfzArticle> implements CmfzArticleService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private CmfzGuruMapper cmfzGuruMapper;
    /**
     * 查询所有文章
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageInfo<CmfzArticle> selectAllArticle(Integer page,Integer limit) {
        PageHelper.startPage(page,limit);
        List<CmfzArticle> cmfzArticles = baseMapper.selectAllArticle();
        return new PageInfo<CmfzArticle>(cmfzArticles);
    }

    /**
     * es+分页
     * @param page
     * @param limit
     * @param key
     * @return
     */
    @Override
    public PageInfo<CmfzArticle> selectArticleByPage(Integer page, Integer limit, String key) throws IOException {

        SearchRequest searchRequest = new SearchRequest("cmfz");
        searchRequest.types("article");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //使用多字段查询
        searchSourceBuilder.query(
                QueryBuilders.multiMatchQuery(key,"articleName","articleContent").analyzer("ik_max_word")
        );

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();

        highlightBuilder.field("articleName");
        highlightBuilder.field("articleContent");

        highlightBuilder.preTags("<span style='color: #F581B1;'>");
        highlightBuilder.postTags("</span>");

        searchSourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(searchSourceBuilder);
        //发送
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //处理响应数据
        SearchHit[] hits = searchResponse.getHits().getHits();

        List<CmfzArticle> list=new ArrayList<>();

        for (SearchHit hit : hits) {
            CmfzArticle cmfzArticle = JSONUtil.toBean(hit.getSourceAsString(), CmfzArticle.class);
            CmfzGuru cmfzGuru = cmfzGuruMapper.selectById(cmfzArticle.getGuruId());
            System.out.println(cmfzGuru);
            cmfzArticle.setCmfzGuru(cmfzGuru);
            if (hit.getHighlightFields().get("articleName")!=null){
                String articleName = hit.getHighlightFields().get("articleName").getFragments()[0].string();
                cmfzArticle.setArticleName(articleName);
            }

            if (hit.getHighlightFields().get("articleContent")!=null){
                String articleContent = hit.getHighlightFields().get("articleContent").getFragments()[0].string();
                cmfzArticle.setArticleContent(articleContent);
            }
            list.add(cmfzArticle);
        }
        //PageHelper.startPage(page,limit);

        PageInfo<CmfzArticle> pageInfo = getPageInfo(page, limit, list);
        return pageInfo;
    }

    /**
     * 逻辑删除
     * @param id
     */
    @Override
    public void deleteArticle(Integer id) {
        baseMapper.deleteById(id);
    }

    /**
     * pagehelper手动分页
     * @param currentPage 当前页
     * @param pageSize
     * @param list
     * @param <T>
     * @return
     */
    public static <T> PageInfo<T> getPageInfo(int currentPage, int pageSize, List<T> list) {
        int total = list.size();
        if (total > pageSize) {
            int toIndex = pageSize * currentPage;
            if (toIndex > total) {
                toIndex = total;
            }
            list = list.subList(pageSize * (currentPage - 1), toIndex);
        }
        Page<T> page = new Page<>(currentPage, pageSize);
        page.addAll(list);
        page.setPages((total + pageSize - 1) / pageSize);
        page.setTotal(total);

        PageInfo<T> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }
}
